package tech.xs.common.framework.util;

import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.core.env.Environment;
import org.springframework.http.ResponseEntity;
import tech.xs.common.framework.domain.exception.BaseException;
import tech.xs.common.framework.domain.model.ApiResult;
import tech.xs.common.framework.holder.SpringContextHolder;
import tech.xs.common.sys.domain.bo.UserDetailsBo;
import tech.xs.common.sys.domain.constant.SysCacheKeyConstant;

import java.util.HashMap;
import java.util.Map;

public class SysUserUtil {


    public static UserDetailsBo getUserDetails(Long userId) {
        RedissonClient redissonClient = SpringContextHolder.getBean(RedissonClient.class);
        RBucket<UserDetailsBo> bucket = redissonClient.getBucket(SysCacheKeyConstant.SYS_USER_DETAILS_CACHE + userId);
        if (bucket.isExists()) {
            return bucket.get();
        }
        Environment environment = SpringContextHolder.getBean(Environment.class);
        Map<String, Long> requestParam = new HashMap<>();
        requestParam.put("userId", userId);
        ResponseEntity<ApiResult> response = DynamicRequestUtil.get(environment.getProperty("framework.service.sys.name"), "/user/getUserDetails", requestParam, ApiResult.class);
        ApiResult<UserDetailsBo> apiResult = response.getBody();
        if (!apiResult.isSuccess()) {
            throw new BaseException("sys服务调用失败 apiResult:" + apiResult);
        }
        return apiResult.getData();
    }

    public static UserDetailsBo getCurrUserDetails() {
        AuthHeaderUtil.AuthHeader authHeader = AuthHeaderUtil.getAuthHeader();
        if (authHeader == null) {
            return null;
        }
        return getUserDetails(authHeader.getUserId());
    }

}
